package com.mock.ems.utils;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;


/**
 * Created by MOCK on 2017/8/9.
 */
public class UploadUtil {

    private static final Logger logger = LoggerFactory.getLogger(UploadUtil.class);
    //构造一个带指定Zone对象的配置类
    private static Configuration cfg = new Configuration(Zone.zone2());
    //...其他参数参考类注释
    private static UploadManager uploadManager = new UploadManager(cfg);
    //...生成上传凭证，然后准备上传
    private static String accessKey = "OW4KK75qLiI15XEX7MZowzlhgS67kWsbxBEcStYg";
    private static String secretKey = "nC1tfparJaHtFhDO_srB4XFEa3C1sMwzAXLg4CDq";
    private static String bucket = "zmzcloud";
    private static Auth auth = Auth.create(accessKey, secretKey);
    private static String upToken = auth.uploadToken(bucket,null,1000000000,null);

    private static final String domain = "http://cdn.zmzcloud.com/";

    public static String upload(File file) {
        try {

            String key = System.nanoTime() + file.getName();
            Response response = uploadManager.put(file, key,upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return domain + putRet.key;
        } catch (Exception ex) {
            //尝试
            logger.error(ex.getMessage(),ex);
            return null;
        }
    }
}
